package com.peng.wx_official_account.service.impl;

import cn.hutool.json.JSONUtil;
import com.peng.wx_official_account.entity.dto.WeChatData;
import com.peng.wx_official_account.entity.dto.WeChatPushDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

@Slf4j
@Service
public class WeChatPushImpl extends WeChatServiceImpl {

    private RestTemplate restTemplate = new RestTemplate();

    private final WeChatData weChatData;

    public WeChatPushImpl(WeChatData weChatData) {
        super(weChatData);
        this.weChatData = weChatData;
    }

    @Override
    public boolean pushMsdData(WeChatPushDto data) {
        String json = JSONUtil.toJsonPrettyStr(data);

        String url = String.format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s", weChatData.getToken());
        URI uri = URI.create(url);
        HttpHeaders headers = new HttpHeaders();
        //设置请求体参数为json
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 用HttpEntity封装整个请求报文
        HttpEntity<String> request = new HttpEntity<>(json, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(uri, request, String.class);
        log.info("response ==> {}", response);

        return true;
    }
}
